define([
  'jquery',
  'underscore',
  'models/User',
  'models/Message',
  'views/Modal',
  'views/media/UsersSelection',
  'hbs!template/media/preview-modal',
  'hbs!template/media/users-selection',
  'hbs!template/users/success-modal',
  "hbs!template/media/actions-modal-footer"
],function($, _, User, Message, Modal, UsersSelection, template_modal, template_users, successTemplate, footerTemplate){
  var InlineUsersSelection = UsersSelection.extend({
    template: template_users,
    
    initialize: function(options) {
      options || (options = {});
      UsersSelection.prototype.initialize.call(this, options);
      this.bind("update:selection", this.render, this);
    },

    getRenderData: function() {
      var data = UsersSelection.prototype.getRenderData.call(this);
      data._flags || (data._flags = {});
      if(this.getReceivers() && this.getReceivers().length > 0) {
        data._flags.showSend  = true;
      }

      return data;
    }
  });
  
  var PhotoAlbumModal = Modal.extend({
    
    events: {
      "click a.page":		"changePage",
      "click button[name=share]":          "share"
//      "click button[name=send]":      "sendMessage"
/*      "click button[name=next]":   "next",
      "click button[name=prev]":   "prev" */
    },
    
    initialize: function(options) {
      options || (options = {});
      this.models = options.models;
      this.position = options.position;
      
      _.bindAll(this,
		'close',
               'keyPressed'); 
      this.template = template_modal;
      this.showUsers = false;

      this.user = new User();
      this.user.fetch();
      // TODO Try to find another way to achieve this.
      $(document).bind('keyup.modal', this.keyPressed);
    },
    
    renderContain: function() {
      $(this.el).html(this.template(this.getRenderData()));

      this.renderFooter();
      
      return this;
    },

    changePage: function(e) {
      e.preventDefault();
      var page = $(e.currentTarget).data("id") ? $(e.currentTarget).data("id") : 1;
      if(page >= 0 && page <= this.models.length) {
        this.position = page;
        this.render();
      }
    },

    next: function() {
      if(this.position+1 <= this.models.length) {
        this.position++;
        this.renderContain();
      }
    },
    
    prev: function() {
      if(this.position-1 >= 0) {
          this.position--;
        this.renderContain();
      }
    },

    keyPressed: function(evt) {
      if(evt.keyCode === 39) {
        this.next();
      } else if(evt.keyCode === 37) {
        this.prev();
      }
    },

    share: function() {
      this.showUsers  = !this.showUsers;
      this.renderFooter();
    },
    
    renderFooter: function() {
      // View for users selection
    
      this.$("#footer").html(footerTemplate(this.getRenderData()));
      if(this.showUsers) {
        var userCollection;
        if(this.user.get('isFamiliar')) {
          userCollection = this.user.internals;
        } else {
          userCollection = this.user.familiars;
        }

        this.usersSelectionView = new InlineUsersSelection({el: this.$("#users-selection"), collection: userCollection, type: this.options.type});
        this.usersSelectionView.bind("action:send", this.sendMessage, this);
        this.usersSelectionView.render();
        userCollection.fetch();
      }


    },
    
    getURLContent: function() {
      return this.models[this.position].get('source') || this.models[this.position].get('content') ||
        this.models[this.position].get('original');
    },
    
    sendMessage: function() {
      var url = this.getURLContent();
      var contents = [{type: this.type || "photo", source: url}];
      var body = "Mensaje con contenido externo.";
      var receivers = this.usersSelectionView.getReceivers();
      var message = new Message({
        receivers: receivers,
        contents: contents,
        body: body
      });

      message.bind("success_save", this.showSuccessMessage, this);
      message.bind("error_save", this.errorHandler, this);
      
      console.log("-------------- Enviando mensaje -----------------");
      console.log(message);
      console.log("-----------------------------------------------");
      message.save();
    },

    showSuccessMessage: function() {
      this.close();
      var modal = new Modal({template: successTemplate});
      modal.render();
    },

    
    getRenderData: function() {
      var data = this.models[this.position].toJSON();
      data._flags || (data._flags = {});
      
      data.pagination = {
        next: this.position < this.models.length ? this.position+1 : 0,
        prev: this.position > 0 ? this.position-1 : 0,
        page: this.position,
        total: this.models.length
      };

      data._flags.showUsers = this.showUsers;
      
      return data;
    }
  });

  return PhotoAlbumModal;
});
